package org.dom4j;

import org.dom4j.tree.DefaultCDATA;
import org.dom4j.tree.DefaultDocument;
import org.dom4j.tree.DefaultElement;
import org.dom4j.tree.DefaultText;

import com.google.gwt.xml.client.Attr;
import com.google.gwt.xml.client.XMLParser;

public class DocumentHelper {
  
  public static Element makeElement(Branch parent, String xpath) {
    String paths[] = xpath.split("/");
    if (parent instanceof Element) {
      for (int i = 0; i < paths.length; i++) {
        Element child = ((Element)parent).element(paths[i]);
        if (child == null) {
          child = ((Element)parent).addElement(paths[i]);
        }
        parent = child;
      }
      return (Element)parent;
    } else {
      throw new UnsupportedOperationException();
    }
  }
  
  public static Document parseText(String text) throws DocumentException {
    com.google.gwt.xml.client.Document gwtDoc = XMLParser.parse(text);
    // convert xml text to dom
    DefaultDocument doc = new DefaultDocument();
    com.google.gwt.xml.client.Element rootElement = gwtDoc.getDocumentElement();
    Element dom4jElement = convertGWTElement(rootElement);
    doc.add(dom4jElement);
    return doc;
  }
  
  private static Element convertGWTElement(com.google.gwt.xml.client.Element element) {
    DefaultElement dom4jElem = new DefaultElement(element.getNodeName());
    for (int i = 0; i < element.getAttributes().getLength(); i++) {
      Attr attrib = (Attr)element.getAttributes().item(i);
      dom4jElem.addAttribute(attrib.getName(), attrib.getValue());
    }
    
    for (int i = 0; i < element.getChildNodes().getLength(); i++) {
      com.google.gwt.xml.client.Node node = element.getChildNodes().item(i);
      if (node instanceof com.google.gwt.xml.client.Element) {
        Element childElem = convertGWTElement((com.google.gwt.xml.client.Element)node);
        dom4jElem.add(childElem);
      } else if (node instanceof com.google.gwt.xml.client.Text) {
        String data = ((com.google.gwt.xml.client.Text)node).getData().trim();
        if (data.length() > 0) {
          DefaultText text = new DefaultText(dom4jElem, data);
          dom4jElem.add(text);
        }
      } else if (node instanceof com.google.gwt.xml.client.CDATASection) {
        DefaultCDATA text = new DefaultCDATA(dom4jElem, ((com.google.gwt.xml.client.Text)node).getData());
        dom4jElem.add(text);  
      } else if (node instanceof com.google.gwt.xml.client.Comment) {
        // ignore for now
      }
    }
    return dom4jElem;
  }
  
  public static Document createDocument() {
    return new DefaultDocument();
  }
}
